package com.office.forum.manage.comments.domain;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class ProcessComments {
    /**
     * 构建评论树
     *
     * @param list
     * @return
     */
    public static List<ForumComments> processComments(List<ForumComments> list) {
        Map<Long, ForumComments> map = new HashMap<>();   // (id, Comment)
        List<ForumComments> result = new ArrayList<>();
        // 将所有根评论加入 map
        for (ForumComments comment : list) {
            if (comment.getParentCommentId() == null)
                result.add(comment);
            map.put(comment.getCommentId(), comment);
        }
        // 子评论加入到父评论的 child 中
        for (ForumComments comment : list) {
            Long id = comment.getParentCommentId();
            if (id != null) {   // 当前评论为子评论
                ForumComments p = map.get(id);
                if (p.getChild() == null)    // child 为空，则创建
                    p.setChild(new ArrayList<>());
                p.getChild().add(comment);
                System.out.println(p.getChild());
            }
        }
        return result;
    }

}
